﻿using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading;
using System.Threading.Tasks;
using Common.Identity;
using Microsoft.Extensions.Logging;

namespace Demo03.RestClient;

/// <summary>
/// 自定义认证头处理器
/// </summary>
public class AuthHeaderHandler : DelegatingHandler
{
    /// <summary>
    /// 日志
    /// </summary>
    private readonly ILogger<AuthHeaderHandler> _logger;

    /// <summary>
    /// 构造函数
    /// </summary>
    /// <param name="logger"></param>
    public AuthHeaderHandler(ILogger<AuthHeaderHandler> logger)
    {
        _logger = logger;
        InnerHandler = new HttpClientHandler();
    }

    /// <summary>
    /// 处理认证头
    /// </summary>
    /// <param name="request"></param>
    /// <param name="cancellationToken"></param>
    /// <returns></returns>
    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,
        CancellationToken cancellationToken)
    {
        var currentBearerToken = IdentityContext.Current?.BearerToken;
        _logger.LogDebug("IdentityContext bearer token: {@token}", currentBearerToken);
        request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", currentBearerToken);

        return await base.SendAsync(request, cancellationToken).ConfigureAwait(false);
    }
}